package com.eelye.util.spring;

import com.eelye.util.enums.ErrorCodeEnum;
import com.eelye.util.exception.CodedException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice
public class CodedExceptionHandler {

    @ExceptionHandler
    public Map<String, Object> resolveException(Exception pe) {
        log.error("统一错误处理捕获到异常。", pe);

        int errCode = ErrorCodeEnum.SystemError.getCode();
        String errStr = "system error.";
        if (pe instanceof CodedException) {
            errCode = ((CodedException) pe).getCode();
            errStr = pe.getMessage();
        }

        Map<String, Object> responseContent = new HashMap<>();
        responseContent.put("errCode", errCode);
        responseContent.put("errMsg", errStr);

        return responseContent;
    }
}
